// MIT License
//
// Copyright (c) 2023-Present - Violet Hansen - (aka HotCakeX on GitHub) - Email Address: spynetgirl@outlook.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// See here for more information: https://github.com/HotCakeX/Harden-Windows-Security/blob/main/LICENSE
//

using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Win32;

namespace HardenSystemSecurity.ExploitMitigation;

internal static class SecurityPolicyRepository
{
	private delegate void ConfigurationApplier(AppMitigations mitigations, ulong configurationState, Action<bool> applyForceFlag, Action<OPTIONVALUE> applyOptionValue);
	private delegate void AuditConfigurationApplier(AppMitigations mitigations, ulong configurationState);

	private readonly struct ConfigurationQueryDescriptor
	{
		internal IMAGE_MITIGATION_POLICY ConfigurationType { get; init; }
		internal ConfigurationApplier Applier { get; init; }
		internal AuditConfigurationApplier? AuditApplier { get; init; }
		internal string ConfigurationName { get; init; }
		internal bool SupportsAuditConfiguration { get; init; }
	}

	private readonly struct PayloadConfigurationQueryDescriptor
	{
		internal ConfigurationApplier Applier { get; init; }
		internal AuditConfigurationApplier AuditApplier { get; init; }
		internal string AttributeName { get; init; }
	}

	private static readonly ConfigurationQueryDescriptor[] ConfigurationDescriptors = [
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageDepPolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.Dep.Enable = ConvertConfigurationStateToOptionValue(state, force => mitigations.Dep.OverrideDEP = force, option => mitigations.Dep.EmulateAtlThunks = option),
			ConfigurationName = "DEP",
			SupportsAuditConfiguration = false
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageAslrPolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => {
                // This is a composite policy, we'll handle it specially
            },
			ConfigurationName = "ASLR",
			SupportsAuditConfiguration = false
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageStrictHandleCheckPolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.StrictHandle.Enable = ConvertConfigurationStateToOptionValue(state, force => mitigations.StrictHandle.OverrideStrictHandle = force, option => { }),
			ConfigurationName = "StrictHandle",
			SupportsAuditConfiguration = false
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageSystemCallDisablePolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => {
                // This is a composite policy, we'll handle it specially
            },
			AuditApplier = (mitigations, state) => {
                // This is a composite policy, we'll handle it specially
            },
			ConfigurationName = "SystemCall",
			SupportsAuditConfiguration = true
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageExtensionPointDisablePolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.ExtensionPoint.DisableExtensionPoints = ConvertConfigurationStateToOptionValue(state, force => mitigations.ExtensionPoint.OverrideExtensionPoint = force, option => { }),
			ConfigurationName = "ExtensionPoint",
			SupportsAuditConfiguration = false
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageDynamicCodePolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.DynamicCode.BlockDynamicCode = ConvertConfigurationStateToOptionValue(state, force => mitigations.DynamicCode.OverrideDynamicCode = force, option => { }),
			AuditApplier = (mitigations, state) => mitigations.DynamicCode.Audit = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			ConfigurationName = "DynamicCode",
			SupportsAuditConfiguration = true
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageControlFlowGuardPolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => {
                // This is a composite policy, we'll handle it specially
            },
			ConfigurationName = "CFG",
			SupportsAuditConfiguration = false
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageSignaturePolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => {
                // This is a composite policy, we'll handle it specially
            },
			AuditApplier = (mitigations, state) => {
                // This is a composite policy, we'll handle it specially
            },
			ConfigurationName = "SignedBinaries",
			SupportsAuditConfiguration = true
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageFontDisablePolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.FontDisable.DisableNonSystemFonts = ConvertConfigurationStateToOptionValue(state, force => mitigations.FontDisable.OverrideFontDisable = force, option => { }),
			AuditApplier = (mitigations, state) => mitigations.FontDisable.Audit = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			ConfigurationName = "FontDisable",
			SupportsAuditConfiguration = true
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageImageLoadPolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => {
                // This is a composite policy, we'll handle it specially
            },
			AuditApplier = (mitigations, state) => {
                // This is a composite policy, we'll handle it specially
            },
			ConfigurationName = "ImageLoad",
			SupportsAuditConfiguration = true
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImagePayloadRestrictionPolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => {
                // This is a composite policy, we'll handle it specially
            },
			AuditApplier = (mitigations, state) => {
                // This is a composite policy, we'll handle it specially
            },
			ConfigurationName = "Payload",
			SupportsAuditConfiguration = true
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageSehopPolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.Sehop.Enable = ConvertConfigurationStateToOptionValue(state, force => mitigations.Sehop.OverrideSEHOP = force, option => mitigations.Sehop.TelemetryOnly = option),
			AuditApplier = (mitigations, state) => mitigations.Sehop.Audit = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			ConfigurationName = "SEHOP",
			SupportsAuditConfiguration = true
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageHeapPolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.Heap.TerminateOnError = ConvertConfigurationStateToOptionValue(state, force => mitigations.Heap.OverrideHeap = force, option => { }),
			ConfigurationName = "Heap",
			SupportsAuditConfiguration = false
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageChildProcessPolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.ChildProcess.DisallowChildProcessCreation = ConvertConfigurationStateToOptionValue(state, force => mitigations.ChildProcess.OverrideChildProcess = force, option => { }),
			AuditApplier = (mitigations, state) => mitigations.ChildProcess.Audit = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			ConfigurationName = "ChildProcess",
			SupportsAuditConfiguration = true
		},
		new() {
			ConfigurationType = IMAGE_MITIGATION_POLICY.ImageUserShadowStackPolicy,
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.UserShadowStack.UserShadowStack = ConvertConfigurationStateToOptionValue(state, force => mitigations.UserShadowStack.OverrideUserShadowStack = force, option => mitigations.UserShadowStack.UserShadowStackStrictMode = option),
			AuditApplier = (mitigations, state) => mitigations.UserShadowStack.AuditUserShadowStack = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			ConfigurationName = "UserShadowStack",
			SupportsAuditConfiguration = true
		}
	];

	private static readonly PayloadConfigurationQueryDescriptor[] PayloadConfigurationDescriptors = [
		new() {
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.Payload.EnableExportAddressFilter = ConvertConfigurationStateToOptionValue(state, force => mitigations.Payload.OverrideEnableExportAddressFilter = force, option => { }),
			AuditApplier = (mitigations, state) => mitigations.Payload.AuditEnableExportAddressFilter = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			AttributeName = "EnableExportAddressFilter"
		},
		new() {
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.Payload.EnableExportAddressFilterPlus = ConvertConfigurationStateToOptionValue(state, force => mitigations.Payload.OverrideEnableExportAddressFilterPlus = force, option => { }),
			AuditApplier = (mitigations, state) => mitigations.Payload.AuditEnableExportAddressFilterPlus = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			AttributeName = "EnableExportAddressFilterPlus"
		},
		new() {
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.Payload.EnableImportAddressFilter = ConvertConfigurationStateToOptionValue(state, force => mitigations.Payload.OverrideEnableImportAddressFilter = force, option => { }),
			AuditApplier = (mitigations, state) => mitigations.Payload.AuditEnableImportAddressFilter = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			AttributeName = "EnableImportAddressFilter"
		},
		new() {
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.Payload.EnableRopStackPivot = ConvertConfigurationStateToOptionValue(state, force => mitigations.Payload.OverrideEnableRopStackPivot = force, option => { }),
			AuditApplier = (mitigations, state) => mitigations.Payload.AuditEnableRopStackPivot = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			AttributeName = "EnableRopStackPivot"
		},
		new() {
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.Payload.EnableRopCallerCheck = ConvertConfigurationStateToOptionValue(state, force => mitigations.Payload.OverrideEnableRopCallerCheck = force, option => { }),
			AuditApplier = (mitigations, state) => mitigations.Payload.AuditEnableRopCallerCheck = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			AttributeName = "EnableRopCallerCheck"
		},
		new() {
			Applier = (mitigations, state, applyForceFlag, applyOptionValue) => mitigations.Payload.EnableRopSimExec = ConvertConfigurationStateToOptionValue(state, force => mitigations.Payload.OverrideEnableRopSimExec = force, option => { }),
			AuditApplier = (mitigations, state) => mitigations.Payload.AuditEnableRopSimExec = ConvertConfigurationStateToOptionValue(state, force => { }, option => { }),
			AttributeName = "EnableRopSimExec"
		}
	];

	private static ulong ConvertOptionValueToConfigurationState(OPTIONVALUE value, bool force, OPTIONVALUE option = OPTIONVALUE.OFF)
	{
		int stateValue = value switch
		{
			OPTIONVALUE.ON => 1,
			OPTIONVALUE.OFF => 2,
			_ => 0,
		};
		RTL_IMAGE_MITIGATION_OPTION_STATE configurationState = (RTL_IMAGE_MITIGATION_OPTION_STATE)stateValue;
		if (force)
			configurationState |= RTL_IMAGE_MITIGATION_OPTION_STATE.RtlMitigationOptionStateForce;
		if (value is OPTIONVALUE.ON && option is OPTIONVALUE.ON)
			configurationState |= RTL_IMAGE_MITIGATION_OPTION_STATE.RtlMitigationOptionStateOption;
		return (ulong)configurationState;
	}

	internal static Result SaveSecurityConfigurationToRegistry(AppMitigations applicationMitigations)
	{
		try
		{
			SecurityConfigurationWriter configurationWriter = new(applicationMitigations);
			return configurationWriter.ExecuteAllConfigurationWrites();
		}
		catch (Exception ex)
		{
			return Result.Failure($"Registry policy write operation failed: {ex.Message}");
		}
	}

	private sealed class SecurityConfigurationWriter(AppMitigations applicationMitigations)
	{
		private readonly AppMitigations _applicationMitigations = applicationMitigations;
		private readonly string? _executablePath = DetermineExecutablePath(applicationMitigations);

		private static string? DetermineExecutablePath(AppMitigations applicationMitigations)
		{
			return string.Equals(applicationMitigations.ProcessName, "System", StringComparison.OrdinalIgnoreCase)
				? null
				: applicationMitigations.ProcessName;
		}

		internal Result ExecuteAllConfigurationWrites()
		{
			List<Result> operationResults = [

				SaveDEPConfiguration(),
				SaveASLRConfiguration(),
				SaveStrictHandleConfiguration(),
				SaveSystemCallConfiguration(),
				SaveExtensionPointConfiguration(),
				SaveDynamicCodeConfiguration(),
				SaveCFGConfiguration(),
				SaveBinarySignatureConfiguration(),
				SaveFontDisableConfiguration(),
				SaveImageLoadConfiguration(),
				SavePayloadConfiguration(),
				SaveSEHOPConfiguration(),
				SaveHeapConfiguration(),
				SaveChildProcessConfiguration(),
				SaveUserShadowStackConfiguration()
			];

			List<Result> failedOperations = operationResults.Where(result => result.IsFailure).ToList();

			return failedOperations.Count > 0
				? Result.Failure($"Failed to write {failedOperations.Count} mitigation policies to registry")
				: Result.Success();
		}

		private Result SaveDEPConfiguration()
		{
			RTL_IMAGE_MITIGATION_DEP_POLICY configurationStructure = new()
			{
				Dep = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Dep.Enable, _applicationMitigations.Dep.OverrideDEP, _applicationMitigations.Dep.EmulateAtlThunks) }
			};

			return ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageDepPolicy, _applicationMitigations.Dep.Flags, configurationStructure, "DEP");
		}

		private Result SaveASLRConfiguration()
		{
			RTL_IMAGE_MITIGATION_ASLR_POLICY configurationStructure = new()
			{
				ForceRelocateImages = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Aslr.ForceRelocateImages, _applicationMitigations.Aslr.OverrideForceRelocateImages, _applicationMitigations.Aslr.RequireInfo) },
				BottomUpRandomization = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Aslr.BottomUp, _applicationMitigations.Aslr.OverrideBottomUp) },
				HighEntropyRandomization = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Aslr.HighEntropy, _applicationMitigations.Aslr.OverrideHighEntropy) }
			};

			return ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageAslrPolicy, _applicationMitigations.Aslr.Flags, configurationStructure, "ASLR");
		}

		private Result SaveStrictHandleConfiguration()
		{
			RTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY configurationStructure = new()
			{
				StrictHandleChecks = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.StrictHandle.Enable, _applicationMitigations.StrictHandle.OverrideStrictHandle) }
			};

			return ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageStrictHandleCheckPolicy, _applicationMitigations.StrictHandle.Flags, configurationStructure, "StrictHandle");
		}

		private Result SaveSystemCallConfiguration()
		{
			RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY configurationStructure = new()
			{
				BlockWin32kSystemCalls = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.SystemCall.DisableWin32kSystemCalls, _applicationMitigations.SystemCall.OverrideSystemCall) },
				BlockFsctlSystemCalls = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.SystemCall.DisableFsctlSystemCalls, _applicationMitigations.SystemCall.OverrideFsctlSystemCall) }
			};

			Result primaryOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageSystemCallDisablePolicy, _applicationMitigations.SystemCall.Flags, configurationStructure, "SystemCall");

			RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY auditConfigurationStructure = new()
			{
				BlockWin32kSystemCalls = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.SystemCall.Audit, false) },
				BlockFsctlSystemCalls = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.SystemCall.AuditFsctlSystemCalls, false) }
			};

			Result auditOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageSystemCallDisablePolicy, 8U | _applicationMitigations.SystemCall.Flags, auditConfigurationStructure, "SystemCall Audit");

			return primaryOperationResult.IsFailure ? primaryOperationResult : auditOperationResult;
		}

		private Result SaveExtensionPointConfiguration()
		{
			RTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY configurationStructure = new()
			{
				DisableExtensionPoints = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.ExtensionPoint.DisableExtensionPoints, _applicationMitigations.ExtensionPoint.OverrideExtensionPoint) }
			};

			return ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageExtensionPointDisablePolicy, _applicationMitigations.ExtensionPoint.Flags, configurationStructure, "ExtensionPoint");
		}

		private Result SaveDynamicCodeConfiguration()
		{
			RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY configurationStructure = new()
			{
				BlockDynamicCode = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.DynamicCode.BlockDynamicCode, _applicationMitigations.DynamicCode.OverrideDynamicCode) }
			};

			Result primaryOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageDynamicCodePolicy, _applicationMitigations.DynamicCode.Flags, configurationStructure, "DynamicCode");

			RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY auditConfigurationStructure = new()
			{
				BlockDynamicCode = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.DynamicCode.Audit, false) }
			};

			Result auditOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageDynamicCodePolicy, 8U | _applicationMitigations.DynamicCode.Flags, auditConfigurationStructure, "DynamicCode Audit");

			return primaryOperationResult.IsFailure ? primaryOperationResult : auditOperationResult;
		}

		private Result SaveCFGConfiguration()
		{
			RTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY configurationStructure = new()
			{
				ControlFlowGuard = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Cfg.Enable, _applicationMitigations.Cfg.OverrideCFG, _applicationMitigations.Cfg.SuppressExports) },
				StrictControlFlowGuard = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Cfg.StrictControlFlowGuard, _applicationMitigations.Cfg.OverrideStrictCFG) }
			};

			return ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageControlFlowGuardPolicy, _applicationMitigations.Cfg.Flags, configurationStructure, "CFG");
		}

		private Result SaveBinarySignatureConfiguration()
		{
			RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY configurationStructure = new()
			{
				BlockNonMicrosoftSignedBinaries = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.BinarySignature.MicrosoftSignedOnly, _applicationMitigations.BinarySignature.OverrideMicrosoftSignedOnly, _applicationMitigations.BinarySignature.AllowStoreSignedBinaries) },
				EnforceSigningOnModuleDependencies = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.BinarySignature.EnforceModuleDependencySigning, _applicationMitigations.BinarySignature.OverrideEnforceModuleDependencySigning) }
			};

			Result primaryOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageSignaturePolicy, _applicationMitigations.BinarySignature.Flags, configurationStructure, "BinarySignature");

			RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY auditConfigurationStructure = new()
			{
				BlockNonMicrosoftSignedBinaries = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.BinarySignature.Audit, false, _applicationMitigations.BinarySignature.AuditStoreSigned) },
				EnforceSigningOnModuleDependencies = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.BinarySignature.AuditEnforceModuleDependencySigning, false) }
			};

			Result auditOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageSignaturePolicy, 8U | _applicationMitigations.BinarySignature.Flags, auditConfigurationStructure, "BinarySignature Audit");

			return primaryOperationResult.IsFailure ? primaryOperationResult : auditOperationResult;
		}

		private Result SaveFontDisableConfiguration()
		{
			RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY configurationStructure = new()
			{
				DisableNonSystemFonts = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.FontDisable.DisableNonSystemFonts, _applicationMitigations.FontDisable.OverrideFontDisable) }
			};

			Result primaryOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageFontDisablePolicy, _applicationMitigations.FontDisable.Flags, configurationStructure, "FontDisable");

			RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY auditConfigurationStructure = new()
			{
				DisableNonSystemFonts = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.FontDisable.Audit, false) }
			};

			Result auditOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageFontDisablePolicy, 8U | _applicationMitigations.FontDisable.Flags, auditConfigurationStructure, "FontDisable Audit");

			return primaryOperationResult.IsFailure ? primaryOperationResult : auditOperationResult;
		}

		private Result SaveImageLoadConfiguration()
		{
			RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY configurationStructure = new()
			{
				BlockRemoteImageLoads = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.ImageLoad.BlockRemoteImageLoads, _applicationMitigations.ImageLoad.OverrideBlockRemoteImageLoads) },
				BlockLowLabelImageLoads = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.ImageLoad.BlockLowLabelImageLoads, _applicationMitigations.ImageLoad.OverrideBlockLowLabel) },
				PreferSystem32 = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.ImageLoad.PreferSystem32, _applicationMitigations.ImageLoad.OverridePreferSystem32) }
			};

			Result primaryOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageImageLoadPolicy, _applicationMitigations.ImageLoad.Flags, configurationStructure, "ImageLoad");

			RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY auditConfigurationStructure = new()
			{
				BlockRemoteImageLoads = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.ImageLoad.AuditRemoteImageLoads, false) },
				BlockLowLabelImageLoads = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.ImageLoad.AuditLowLabelImageLoads, false) },
				PreferSystem32 = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.ImageLoad.AuditPreferSystem32, false) }
			};

			Result auditOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageImageLoadPolicy, 8U | _applicationMitigations.ImageLoad.Flags, auditConfigurationStructure, "ImageLoad Audit");

			return primaryOperationResult.IsFailure ? primaryOperationResult : auditOperationResult;
		}

		private Result SavePayloadConfiguration()
		{
			Result moduleValidationResult = PerformEAFModuleValidation();
			if (moduleValidationResult.IsFailure)
				return moduleValidationResult;

			RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY configurationStructure = new()
			{
				EnableExportAddressFilter = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.EnableExportAddressFilter, _applicationMitigations.Payload.OverrideEnableExportAddressFilter) },
				EnableExportAddressFilterPlus = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.EnableExportAddressFilterPlus, _applicationMitigations.Payload.OverrideEnableExportAddressFilterPlus) },
				EnableImportAddressFilter = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.EnableImportAddressFilter, _applicationMitigations.Payload.OverrideEnableImportAddressFilter) },
				EnableRopStackPivot = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.EnableRopStackPivot, _applicationMitigations.Payload.OverrideEnableRopStackPivot) },
				EnableRopCallerCheck = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.EnableRopCallerCheck, _applicationMitigations.Payload.OverrideEnableRopCallerCheck) },
				EnableRopSimExec = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.EnableRopSimExec, _applicationMitigations.Payload.OverrideEnableRopSimExec) }
			};

			PopulateEAFModuleArray(ref configurationStructure);

			Result primaryOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImagePayloadRestrictionPolicy, _applicationMitigations.Payload.Flags, configurationStructure, "Payload");

			RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY auditConfigurationStructure = new()
			{
				EnableExportAddressFilter = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.AuditEnableExportAddressFilter, false) },
				EnableExportAddressFilterPlus = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.AuditEnableExportAddressFilterPlus, false) },
				EnableImportAddressFilter = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.AuditEnableImportAddressFilter, false) },
				EnableRopStackPivot = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.AuditEnableRopStackPivot, false) },
				EnableRopCallerCheck = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.AuditEnableRopCallerCheck, false) },
				EnableRopSimExec = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Payload.AuditEnableRopSimExec, false) }
			};

			Result auditOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImagePayloadRestrictionPolicy, 8U | _applicationMitigations.Payload.Flags, auditConfigurationStructure, "Payload Audit");

			return primaryOperationResult.IsFailure ? primaryOperationResult : auditOperationResult;
		}

		private Result PerformEAFModuleValidation()
		{
			if (_applicationMitigations.Payload.EAFModules.Count is 0)
				return Result.Success();

			const int maximumAllowedModules = 32;
			const int maximumModuleListLength = 512;

			if (_applicationMitigations.Payload.EAFModules.Count > maximumAllowedModules)
			{
				Logger.Write($"EAF+ module validation failed: {_applicationMitigations.Payload.EAFModules.Count} modules specified, but maximum allowed is {maximumAllowedModules}");
				return Result.Failure($"EAF+ module count exceeds maximum limit of {maximumAllowedModules}");
			}

			string moduleListContent = string.Join(";", _applicationMitigations.Payload.EAFModules.Where(module => !string.IsNullOrEmpty(module))) + ";";

			if (moduleListContent.Length > maximumModuleListLength)
			{
				Logger.Write($"EAF+ module validation failed: Module list length {moduleListContent.Length} exceeds maximum of {maximumModuleListLength} characters");
				return Result.Failure($"EAF+ module list length exceeds maximum of {maximumModuleListLength} characters");
			}

			return Result.Success();
		}

		// Write module list directly into the fixed buffer.
		private unsafe void PopulateEAFModuleArray(ref RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY configurationStructure)
		{
			if (_applicationMitigations.Payload.EAFModules.Count == 0)
			{
				return;
			}

			// Build semicolon-delimited list with trailing ';'
			string moduleListContent = string.Join(";", _applicationMitigations.Payload.EAFModules.Where(m => !string.IsNullOrEmpty(m))) + ";";

			// Truncate to (512 - 1) to reserve a null terminator if longer.
			const int MaxChars = 512;
			int copyLen = moduleListContent.Length > (MaxChars - 1) ? (MaxChars - 1) : moduleListContent.Length;

			// Write directly via indexing
			for (int i = 0; i < MaxChars; i++)
			{
				configurationStructure.ModuleList[i] = '\0';
			}
			for (int i = 0; i < copyLen; i++)
			{
				configurationStructure.ModuleList[i] = moduleListContent[i];
			}
			configurationStructure.ModuleList[copyLen] = '\0';
		}

		private Result SaveSEHOPConfiguration()
		{
			RTL_IMAGE_MITIGATION_SEHOP_POLICY configurationStructure = new()
			{
				Sehop = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Sehop.Enable, _applicationMitigations.Sehop.OverrideSEHOP, _applicationMitigations.Sehop.TelemetryOnly) }
			};

			Result primaryOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageSehopPolicy, _applicationMitigations.Sehop.Flags, configurationStructure, "SEHOP");

			RTL_IMAGE_MITIGATION_SEHOP_POLICY auditConfigurationStructure = new()
			{
				Sehop = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Sehop.Audit, false) }
			};

			Result auditOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageSehopPolicy, 8U | _applicationMitigations.Sehop.Flags, auditConfigurationStructure, "SEHOP Audit");

			return primaryOperationResult.IsFailure ? primaryOperationResult : auditOperationResult;
		}

		private Result SaveHeapConfiguration()
		{
			RTL_IMAGE_MITIGATION_HEAP_POLICY configurationStructure = new()
			{
				TerminateOnHeapErrors = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.Heap.TerminateOnError, _applicationMitigations.Heap.OverrideHeap) }
			};

			return ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageHeapPolicy, _applicationMitigations.Heap.Flags, configurationStructure, "Heap");
		}

		private Result SaveChildProcessConfiguration()
		{
			RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY configurationStructure = new()
			{
				DisallowChildProcessCreation = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.ChildProcess.DisallowChildProcessCreation, _applicationMitigations.ChildProcess.OverrideChildProcess) }
			};

			Result primaryOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageChildProcessPolicy, _applicationMitigations.ChildProcess.Flags, configurationStructure, "ChildProcess");

			RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY auditConfigurationStructure = new()
			{
				DisallowChildProcessCreation = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.ChildProcess.Audit, false) }
			};

			Result auditOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageChildProcessPolicy, 8U | _applicationMitigations.ChildProcess.Flags, auditConfigurationStructure, "ChildProcess Audit");

			return primaryOperationResult.IsFailure ? primaryOperationResult : auditOperationResult;
		}

		private Result SaveUserShadowStackConfiguration()
		{
			RTL_IMAGE_MITIGATION_USER_SHADOW_STACK_POLICY configurationStructure = new()
			{
				UserShadowStack = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.UserShadowStack.UserShadowStack, _applicationMitigations.UserShadowStack.OverrideUserShadowStack, _applicationMitigations.UserShadowStack.UserShadowStackStrictMode) }
			};

			Result primaryOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageUserShadowStackPolicy, _applicationMitigations.UserShadowStack.Flags, configurationStructure, "UserShadowStack");

			RTL_IMAGE_MITIGATION_USER_SHADOW_STACK_POLICY auditConfigurationStructure = new()
			{
				UserShadowStack = { PolicyState = ConvertOptionValueToConfigurationState(_applicationMitigations.UserShadowStack.AuditUserShadowStack, false) }
			};

			Result auditOperationResult = ExecuteConfigurationSave(IMAGE_MITIGATION_POLICY.ImageUserShadowStackPolicy, 8U | _applicationMitigations.UserShadowStack.Flags, auditConfigurationStructure, "UserShadowStack Audit");

			return primaryOperationResult.IsFailure ? primaryOperationResult : auditOperationResult;
		}

		private Result ExecuteConfigurationSave<T>(
			IMAGE_MITIGATION_POLICY configurationType,
			uint flags,
			T configurationStructure,
			string configurationName) where T : unmanaged
		{
			try
			{
				int operationResult = Main.SetImageMitigationPolicy(_executablePath, configurationType, flags, configurationStructure);

				if (operationResult != 0)
				{
					Logger.Write($"Mitigation policy application failed for {configurationName}: Error code 0x{operationResult:X8}");
					return Result.Failure($"Failed to apply {configurationName} policy: Error code 0x{operationResult:X8}");
				}

				return Result.Success();
			}
			catch (Exception ex)
			{
				Logger.Write($"Exception occurred while applying {configurationName} policy: {ex.Message}");
				return Result.Failure($"Exception during {configurationName} policy application: {ex.Message}");
			}
		}
	}

	private static OPTIONVALUE ConvertConfigurationStateToOptionValue(
	  ulong configurationState,
	  Action<bool> applyForceFlag,
	  Action<OPTIONVALUE> applyOptionValue)
	{
		OPTIONVALUE resultValue = (configurationState & 3UL) switch
		{
			1 => OPTIONVALUE.ON,
			2 => OPTIONVALUE.OFF,
			_ => OPTIONVALUE.NOTSET,
		};
		applyForceFlag((configurationState & 4UL) > 0UL);
		applyOptionValue(((long)configurationState & 8L) != 0L ? OPTIONVALUE.ON : OPTIONVALUE.OFF);
		return resultValue;
	}

	private static bool AttemptConfigurationQuery<T>(string? executableName, IMAGE_MITIGATION_POLICY configurationType, uint flags, out T configurationStructure, string configurationName) where T : unmanaged
	{
		configurationStructure = default;
		int queryResult = Main.QueryImageMitigationPolicy(executableName, configurationType, flags, ref configurationStructure);

		switch (queryResult)
		{
			case -1073741772: // 0xC0000034 - Object not found
				return false;
			case 0: // Success
				return true;
			default:
				Logger.Write($"Registry query warning for {configurationName}: Error code 0x{queryResult:X8}");
				return false;
		}
	}

	private static void HandleASLRConfigurationProcessing(AppMitigations mitigations, RTL_IMAGE_MITIGATION_ASLR_POLICY configurationStructure)
	{
		mitigations.Aslr.ForceRelocateImages = ConvertConfigurationStateToOptionValue(configurationStructure.ForceRelocateImages.PolicyState, force => mitigations.Aslr.OverrideForceRelocateImages = force, option => mitigations.Aslr.RequireInfo = option);
		mitigations.Aslr.BottomUp = ConvertConfigurationStateToOptionValue(configurationStructure.BottomUpRandomization.PolicyState, force => mitigations.Aslr.OverrideBottomUp = force, option => { });
		mitigations.Aslr.HighEntropy = ConvertConfigurationStateToOptionValue(configurationStructure.HighEntropyRandomization.PolicyState, force => mitigations.Aslr.OverrideHighEntropy = force, option => { });
	}

	private static void HandleSystemCallConfigurationProcessing(AppMitigations mitigations, RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY configurationStructure, bool isAuditProcessing)
	{
		if (isAuditProcessing)
		{
			mitigations.SystemCall.Audit = ConvertConfigurationStateToOptionValue(configurationStructure.BlockWin32kSystemCalls.PolicyState, force => { }, option => { });
			mitigations.SystemCall.AuditFsctlSystemCalls = ConvertConfigurationStateToOptionValue(configurationStructure.BlockFsctlSystemCalls.PolicyState, force => { }, option => { });
		}
		else
		{
			mitigations.SystemCall.DisableWin32kSystemCalls = ConvertConfigurationStateToOptionValue(configurationStructure.BlockWin32kSystemCalls.PolicyState, force => mitigations.SystemCall.OverrideSystemCall = force, option => { });
			mitigations.SystemCall.DisableFsctlSystemCalls = ConvertConfigurationStateToOptionValue(configurationStructure.BlockFsctlSystemCalls.PolicyState, force => mitigations.SystemCall.OverrideFsctlSystemCall = force, option => { });
		}
	}

	private static void HandleCFGConfigurationProcessing(AppMitigations mitigations, RTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY configurationStructure)
	{
		mitigations.Cfg.Enable = ConvertConfigurationStateToOptionValue(configurationStructure.ControlFlowGuard.PolicyState, force => mitigations.Cfg.OverrideCFG = force, option => mitigations.Cfg.SuppressExports = option);
		mitigations.Cfg.StrictControlFlowGuard = ConvertConfigurationStateToOptionValue(configurationStructure.StrictControlFlowGuard.PolicyState, force => mitigations.Cfg.OverrideStrictCFG = force, option => { });
	}

	private static void HandleBinarySignatureConfigurationProcessing(AppMitigations mitigations, RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY configurationStructure, bool isAuditProcessing)
	{
		if (isAuditProcessing)
		{
			mitigations.BinarySignature.Audit = ConvertConfigurationStateToOptionValue(configurationStructure.BlockNonMicrosoftSignedBinaries.PolicyState, force => { }, option => mitigations.BinarySignature.AuditStoreSigned = option);
			mitigations.BinarySignature.AuditEnforceModuleDependencySigning = ConvertConfigurationStateToOptionValue(configurationStructure.EnforceSigningOnModuleDependencies.PolicyState, force => { }, option => { });
		}
		else
		{
			mitigations.BinarySignature.MicrosoftSignedOnly = ConvertConfigurationStateToOptionValue(configurationStructure.BlockNonMicrosoftSignedBinaries.PolicyState, force => mitigations.BinarySignature.OverrideMicrosoftSignedOnly = force, option => mitigations.BinarySignature.AllowStoreSignedBinaries = option);
			mitigations.BinarySignature.EnforceModuleDependencySigning = ConvertConfigurationStateToOptionValue(configurationStructure.EnforceSigningOnModuleDependencies.PolicyState, force => mitigations.BinarySignature.OverrideEnforceModuleDependencySigning = force, option => { });
		}
	}

	private static void HandleImageLoadConfigurationProcessing(AppMitigations mitigations, RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY configurationStructure, bool isAuditProcessing)
	{
		if (isAuditProcessing)
		{
			mitigations.ImageLoad.AuditRemoteImageLoads = ConvertConfigurationStateToOptionValue(configurationStructure.BlockRemoteImageLoads.PolicyState, force => { }, option => { });
			mitigations.ImageLoad.AuditLowLabelImageLoads = ConvertConfigurationStateToOptionValue(configurationStructure.BlockLowLabelImageLoads.PolicyState, force => { }, option => { });
			mitigations.ImageLoad.AuditPreferSystem32 = ConvertConfigurationStateToOptionValue(configurationStructure.PreferSystem32.PolicyState, force => { }, option => { });
		}
		else
		{
			mitigations.ImageLoad.BlockRemoteImageLoads = ConvertConfigurationStateToOptionValue(configurationStructure.BlockRemoteImageLoads.PolicyState, force => mitigations.ImageLoad.OverrideBlockRemoteImageLoads = force, option => { });
			mitigations.ImageLoad.BlockLowLabelImageLoads = ConvertConfigurationStateToOptionValue(configurationStructure.BlockLowLabelImageLoads.PolicyState, force => mitigations.ImageLoad.OverrideBlockLowLabel = force, option => { });
			mitigations.ImageLoad.PreferSystem32 = ConvertConfigurationStateToOptionValue(configurationStructure.PreferSystem32.PolicyState, force => mitigations.ImageLoad.OverridePreferSystem32 = force, option => { });
		}
	}

	private static void HandlePayloadConfigurationProcessing(AppMitigations mitigations, RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY configurationStructure, bool isAuditProcessing)
	{
		if (isAuditProcessing)
		{
			foreach (PayloadConfigurationQueryDescriptor queryDescriptor in PayloadConfigurationDescriptors)
			{
				switch (queryDescriptor.AttributeName)
				{
					case "EnableExportAddressFilter":
						queryDescriptor.AuditApplier(mitigations, configurationStructure.EnableExportAddressFilter.PolicyState);
						break;
					case "EnableExportAddressFilterPlus":
						queryDescriptor.AuditApplier(mitigations, configurationStructure.EnableExportAddressFilterPlus.PolicyState);
						break;
					case "EnableImportAddressFilter":
						queryDescriptor.AuditApplier(mitigations, configurationStructure.EnableImportAddressFilter.PolicyState);
						break;
					case "EnableRopStackPivot":
						queryDescriptor.AuditApplier(mitigations, configurationStructure.EnableRopStackPivot.PolicyState);
						break;
					case "EnableRopCallerCheck":
						queryDescriptor.AuditApplier(mitigations, configurationStructure.EnableRopCallerCheck.PolicyState);
						break;
					case "EnableRopSimExec":
						queryDescriptor.AuditApplier(mitigations, configurationStructure.EnableRopSimExec.PolicyState);
						break;
					default:
						break;
				}
			}
		}
		else
		{
			foreach (PayloadConfigurationQueryDescriptor queryDescriptor in PayloadConfigurationDescriptors)
			{
				switch (queryDescriptor.AttributeName)
				{
					case "EnableExportAddressFilter":
						queryDescriptor.Applier(mitigations, configurationStructure.EnableExportAddressFilter.PolicyState, force => { }, option => { });
						break;
					case "EnableExportAddressFilterPlus":
						queryDescriptor.Applier(mitigations, configurationStructure.EnableExportAddressFilterPlus.PolicyState, force => { }, option => { });
						break;
					case "EnableImportAddressFilter":
						queryDescriptor.Applier(mitigations, configurationStructure.EnableImportAddressFilter.PolicyState, force => { }, option => { });
						break;
					case "EnableRopStackPivot":
						queryDescriptor.Applier(mitigations, configurationStructure.EnableRopStackPivot.PolicyState, force => { }, option => { });
						break;
					case "EnableRopCallerCheck":
						queryDescriptor.Applier(mitigations, configurationStructure.EnableRopCallerCheck.PolicyState, force => { }, option => { });
						break;
					case "EnableRopSimExec":
						queryDescriptor.Applier(mitigations, configurationStructure.EnableRopSimExec.PolicyState, force => { }, option => { });
						break;
					default:
						break;
				}
			}

			// Handle module list by extracting it from the fixed buffer safely.
			unsafe
			{
				const int MaxChars = 512;

				int length = 0;
				while (length < MaxChars)
				{
					char c = configurationStructure.ModuleList[length];
					if (c == '\0')
					{
						break;
					}
					length++;
				}

				if (length > 0)
				{
					char[] temp = new char[length];
					for (int i = 0; i < length; i++)
					{
						temp[i] = configurationStructure.ModuleList[i];
					}

					string moduleListData = new(temp);

					if (!string.IsNullOrEmpty(moduleListData))
					{
						char[] separators = [';'];
						mitigations.Payload.EAFModules.Clear();

						foreach (string moduleEntry in moduleListData.Split(separators, StringSplitOptions.RemoveEmptyEntries))
						{
							if (!mitigations.Payload.EAFModules.Contains(moduleEntry, StringComparer.Ordinal))
							{
								mitigations.Payload.EAFModules.Add(moduleEntry);
							}
						}
					}
				}
			}
		}
	}

	private static Result<AppMitigations> CreateCompleteSecurityConfiguration(string? executableName)
	{
		try
		{
			AppMitigations mitigations = new(executableName);

			// Process each policy using the query array
			foreach (ConfigurationQueryDescriptor queryDescriptor in ConfigurationDescriptors)
			{
				switch (queryDescriptor.ConfigurationType)
				{
					case IMAGE_MITIGATION_POLICY.ImageDepPolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_DEP_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_DEP_POLICY depConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							queryDescriptor.Applier(mitigations, depConfigurationStructure.Dep.PolicyState, force => { }, option => { });
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageAslrPolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_ASLR_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_ASLR_POLICY aslrConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							HandleASLRConfigurationProcessing(mitigations, aslrConfigurationStructure);
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageStrictHandleCheckPolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY strictHandleConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							queryDescriptor.Applier(mitigations, strictHandleConfigurationStructure.StrictHandleChecks.PolicyState, force => { }, option => { });
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageSystemCallDisablePolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY systemCallConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							HandleSystemCallConfigurationProcessing(mitigations, systemCallConfigurationStructure, false);
						}
						if (queryDescriptor.SupportsAuditConfiguration && AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY>(executableName, queryDescriptor.ConfigurationType, 8U, out RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY systemCallAuditConfigurationStructure, queryDescriptor.ConfigurationName + " Audit"))
						{
							HandleSystemCallConfigurationProcessing(mitigations, systemCallAuditConfigurationStructure, true);
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageExtensionPointDisablePolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY extensionPointConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							queryDescriptor.Applier(mitigations, extensionPointConfigurationStructure.DisableExtensionPoints.PolicyState, force => { }, option => { });
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageDynamicCodePolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY dynamicCodeConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							queryDescriptor.Applier(mitigations, dynamicCodeConfigurationStructure.BlockDynamicCode.PolicyState, force => { }, option => { });
						}
						if (queryDescriptor.SupportsAuditConfiguration && AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY>(executableName, queryDescriptor.ConfigurationType, 8U, out RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY dynamicCodeAuditConfigurationStructure, queryDescriptor.ConfigurationName + " Audit"))
						{
							queryDescriptor.AuditApplier!(mitigations, dynamicCodeAuditConfigurationStructure.BlockDynamicCode.PolicyState);
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageControlFlowGuardPolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY cfgConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							HandleCFGConfigurationProcessing(mitigations, cfgConfigurationStructure);
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageSignaturePolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY binarySignatureConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							HandleBinarySignatureConfigurationProcessing(mitigations, binarySignatureConfigurationStructure, false);
						}
						if (queryDescriptor.SupportsAuditConfiguration && AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY>(executableName, queryDescriptor.ConfigurationType, 8U, out RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY binarySignatureAuditConfigurationStructure, queryDescriptor.ConfigurationName + " Audit"))
						{
							HandleBinarySignatureConfigurationProcessing(mitigations, binarySignatureAuditConfigurationStructure, true);
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageFontDisablePolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY fontDisableConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							queryDescriptor.Applier(mitigations, fontDisableConfigurationStructure.DisableNonSystemFonts.PolicyState, force => { }, option => { });
						}
						if (queryDescriptor.SupportsAuditConfiguration && AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY>(executableName, queryDescriptor.ConfigurationType, 8U, out RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY fontDisableAuditConfigurationStructure, queryDescriptor.ConfigurationName + " Audit"))
						{
							queryDescriptor.AuditApplier!(mitigations, fontDisableAuditConfigurationStructure.DisableNonSystemFonts.PolicyState);
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageImageLoadPolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY imageLoadConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							HandleImageLoadConfigurationProcessing(mitigations, imageLoadConfigurationStructure, false);
						}
						if (queryDescriptor.SupportsAuditConfiguration && AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY>(executableName, queryDescriptor.ConfigurationType, 8U, out RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY imageLoadAuditConfigurationStructure, queryDescriptor.ConfigurationName + " Audit"))
						{
							HandleImageLoadConfigurationProcessing(mitigations, imageLoadAuditConfigurationStructure, true);
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImagePayloadRestrictionPolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY payloadConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							HandlePayloadConfigurationProcessing(mitigations, payloadConfigurationStructure, false);
						}
						if (queryDescriptor.SupportsAuditConfiguration && AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY>(executableName, queryDescriptor.ConfigurationType, 8U, out RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY payloadAuditConfigurationStructure, queryDescriptor.ConfigurationName + " audit"))
						{
							HandlePayloadConfigurationProcessing(mitigations, payloadAuditConfigurationStructure, true);
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageSehopPolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_SEHOP_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_SEHOP_POLICY sehopConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							queryDescriptor.Applier(mitigations, sehopConfigurationStructure.Sehop.PolicyState, force => { }, option => { });
						}
						if (queryDescriptor.SupportsAuditConfiguration && AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_SEHOP_POLICY>(executableName, queryDescriptor.ConfigurationType, 8U, out RTL_IMAGE_MITIGATION_SEHOP_POLICY sehopAuditConfigurationStructure, queryDescriptor.ConfigurationName + " Audit"))
						{
							queryDescriptor.AuditApplier!(mitigations, sehopAuditConfigurationStructure.Sehop.PolicyState);
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageHeapPolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_HEAP_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_HEAP_POLICY heapConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							queryDescriptor.Applier(mitigations, heapConfigurationStructure.TerminateOnHeapErrors.PolicyState, force => { }, option => { });
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageChildProcessPolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY childProcessConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							queryDescriptor.Applier(mitigations, childProcessConfigurationStructure.DisallowChildProcessCreation.PolicyState, force => { }, option => { });
						}
						if (queryDescriptor.SupportsAuditConfiguration && AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY>(executableName, queryDescriptor.ConfigurationType, 8U, out RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY childProcessAuditConfigurationStructure, queryDescriptor.ConfigurationName + " Audit"))
						{
							queryDescriptor.AuditApplier!(mitigations, childProcessAuditConfigurationStructure.DisallowChildProcessCreation.PolicyState);
						}
						break;

					case IMAGE_MITIGATION_POLICY.ImageUserShadowStackPolicy:
						if (AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_USER_SHADOW_STACK_POLICY>(executableName, queryDescriptor.ConfigurationType, 0U, out RTL_IMAGE_MITIGATION_USER_SHADOW_STACK_POLICY userShadowStackConfigurationStructure, queryDescriptor.ConfigurationName))
						{
							queryDescriptor.Applier(mitigations, userShadowStackConfigurationStructure.UserShadowStack.PolicyState, force => { }, option => { });
						}
						if (queryDescriptor.SupportsAuditConfiguration && AttemptConfigurationQuery<RTL_IMAGE_MITIGATION_USER_SHADOW_STACK_POLICY>(executableName, queryDescriptor.ConfigurationType, 8U, out RTL_IMAGE_MITIGATION_USER_SHADOW_STACK_POLICY userShadowStackAuditConfigurationStructure, queryDescriptor.ConfigurationName + " Audit"))
						{
							queryDescriptor.AuditApplier!(mitigations, userShadowStackAuditConfigurationStructure.UserShadowStack.PolicyState);
						}
						break;
					case IMAGE_MITIGATION_POLICY.ImageMitigationOptionsMask:
						break;
					case IMAGE_MITIGATION_POLICY.MaxImageMitigationPolicy:
						break;
					default:
						break;
				}
			}

			return Result<AppMitigations>.Success(mitigations);
		}
		catch (Exception ex)
		{
			return Result<AppMitigations>.Failure($"Registry policy build operation failed: {ex.Message}");
		}
	}

	internal static Result<List<AppMitigations>> RetrieveSecurityConfigurationListFromRegistry(string? processName)
	{
		try
		{
			List<AppMitigations> configurationListFromRegistry = [];
			RegistryKey? primaryRegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options");
			if (primaryRegistryKey is null)
				return Result<List<AppMitigations>>.Failure("Registry access denied: Unable to open Image File Execution Options key");

			foreach (string subKeyName1 in primaryRegistryKey.GetSubKeyNames())
			{
				if (processName is null || string.Equals(subKeyName1, processName, StringComparison.OrdinalIgnoreCase))
				{
					RegistryKey? secondaryRegistryKey = primaryRegistryKey.OpenSubKey(subKeyName1);
					if (secondaryRegistryKey is not null)
					{
						if (secondaryRegistryKey.GetValue("MitigationOptions") is not null || secondaryRegistryKey.GetValue("MitigationAuditOptions") is not null)
						{
							Result<AppMitigations> configurationResult = CreateCompleteSecurityConfiguration(subKeyName1);
							if (configurationResult.IsSuccess)
							{
								AppMitigations applicationMitigations = configurationResult.Value;
								applicationMitigations.Source = "Registry";
								configurationListFromRegistry.Add(applicationMitigations);
							}
							else
							{
								Logger.Write($"Registry policy read warning for '{subKeyName1}': {configurationResult.Error}");
							}
						}
						if (secondaryRegistryKey.GetValue("UseFilter") is not null)
						{
							foreach (string subKeyName2 in secondaryRegistryKey.GetSubKeyNames())
							{
								RegistryKey? tertiaryRegistryKey = secondaryRegistryKey.OpenSubKey(subKeyName2);
								if (tertiaryRegistryKey is not null)
								{
									object? filterPathValue = tertiaryRegistryKey.GetValue("FilterFullPath");
									if (filterPathValue is not null && tertiaryRegistryKey.GetValueKind("FilterFullPath") is RegistryValueKind.String && (tertiaryRegistryKey.GetValue("MitigationOptions") is not null || tertiaryRegistryKey.GetValue("MitigationAuditOptions") is not null))
									{
										Result<AppMitigations> configurationResult = CreateCompleteSecurityConfiguration(filterPathValue.ToString());
										if (configurationResult.IsSuccess)
										{
											AppMitigations applicationMitigations = configurationResult.Value;
											applicationMitigations.Source = "Registry";
											configurationListFromRegistry.Add(applicationMitigations);
										}
										else
										{
											Logger.Write($"Registry policy read warning for filter path '{filterPathValue}': {configurationResult.Error}");
										}
									}
								}
							}
						}
					}
				}
			}
			return Result<List<AppMitigations>>.Success(configurationListFromRegistry);
		}
		catch (Exception ex)
		{
			return Result<List<AppMitigations>>.Failure($"Registry enumeration operation failed: {ex.Message}");
		}
	}

	internal static Result<List<AppMitigations>> RetrieveSecurityConfigurationFromRegistryByName(string processNameOrPath)
	{
		try
		{
			string fileName = Path.GetFileName(processNameOrPath);
			Result<List<AppMitigations>> configurationListResult = RetrieveSecurityConfigurationListFromRegistry(fileName);
			if (configurationListResult.IsFailure)
				return configurationListResult;

			List<AppMitigations> configurationListFromRegistry = configurationListResult.Value;

			List<AppMitigations> configurationFromRegistryByName = [];

			bool isExactMatch = string.Equals(fileName, processNameOrPath, StringComparison.OrdinalIgnoreCase);

			foreach (AppMitigations applicationMitigations in configurationListFromRegistry)
			{
				if (isExactMatch && string.Equals(applicationMitigations.ProcessName, processNameOrPath, StringComparison.OrdinalIgnoreCase) || !isExactMatch && string.Equals(Path.GetFileName(applicationMitigations.ProcessName), processNameOrPath, StringComparison.OrdinalIgnoreCase))
					configurationFromRegistryByName.Add(applicationMitigations);
			}
			if (isExactMatch && configurationFromRegistryByName.Count is 0)
			{
				foreach (AppMitigations applicationMitigations in configurationListFromRegistry)
				{
					if (string.Equals(applicationMitigations.ProcessName, fileName, StringComparison.OrdinalIgnoreCase))
						configurationFromRegistryByName.Add(applicationMitigations);
				}
			}
			return Result<List<AppMitigations>>.Success(configurationFromRegistryByName);
		}
		catch (Exception ex)
		{
			return Result<List<AppMitigations>>.Failure($"Registry policy search operation failed: {ex.Message}");
		}
	}

	internal static Result<AppMitigations> RetrieveSystemSecurityConfiguration()
	{
		try
		{
			Result<AppMitigations> configurationResult = CreateCompleteSecurityConfiguration(null);
			if (configurationResult.IsFailure)
				return configurationResult;

			AppMitigations systemConfiguration = configurationResult.Value;
			systemConfiguration.Source = "System Defaults";
			systemConfiguration.ProcessName = "System";
			return Result<AppMitigations>.Success(systemConfiguration);
		}
		catch (Exception ex)
		{
			return Result<AppMitigations>.Failure($"System policy retrieval operation failed: {ex.Message}");
		}
	}
}
